if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                keys.push(k);
            }
        }
        return keys;
    };
}

var vkcontrols = {
	needReact:true,
	disable: function(el) {
		el.setAttribute("disabled", "true");
	},
	enable: function(el) {
		el.removeAttribute("disabled");
	},
	popup: function(title, text) {
		try {
			Components.classes['@mozilla.org/alerts-service;1'].getService(Components.interfaces.nsIAlertsService).showAlertNotification("chrome://vkcontrols/content/play.png", title, text, false, '', null);
		} catch(e) {
			var image = "chrome://vkcontrols/content/play.png";
			var win = Components.classes['@mozilla.org/embedcomp/window-watcher;1'].getService(Components.interfaces.nsIWindowWatcher).openWindow(null, 'chrome://vkcontrols/content/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null);
			win.arguments = [image, title, text, false, ''];
		}
	},
	popupNowPlaing: function() {
		setTimeout(function() { vkcontrols.popup("Играет", vkcontrols.unesc(vkcontrols.w.audioPlayer.lastSong[5]) + " - " + vkcontrols.unesc(vkcontrols.w.audioPlayer.lastSong[6])); }, 500);
	},
	padLeft:function(number, width, char) {
		if (!char) char = "0";
		var len = ("" + number).length;
		var r = "";
		for(var i = 0; i < width - len; i++) r += char;
		return r + number;
	},
	switchEnabled:function(enabled) {
		if (enabled) {
			this.enable(document.getElementById('vkcontrols-playpausebutton'));
			this.enable(document.getElementById('vkcontrols-prevbutton'));
			this.enable(document.getElementById('vkcontrols-repeatbutton'));
			this.enable(document.getElementById('vkcontrols-nextbutton'));
			this.enable(document.getElementById('vkcontrols-position'));
			this.enable(document.getElementById('vkcontrols-volume'));
			this.enable(document.getElementById('vkcontrols-speakerbutton'));
		} else {
			document.getElementById('vkcontrols-playpausebutton').checked = false;
			this.disable(document.getElementById('vkcontrols-playpausebutton'));
			this.disable(document.getElementById('vkcontrols-prevbutton'));
			this.disable(document.getElementById('vkcontrols-repeatbutton'));
			this.disable(document.getElementById('vkcontrols-nextbutton'));
			this.disable(document.getElementById('vkcontrols-position'));
			this.disable(document.getElementById('vkcontrols-volume'));
			this.disable(document.getElementById('vkcontrols-speakerbutton'));
			this.needReact = false;
			this.volumeSlider.value = this.positionSlider.value = 0;
			this.volumeLabel.value = "--";
			this.positionLabel.value = "--:--";
			this.positionProgress.style.marginLeft = "240px";
			this.trackName.value = "Ничего не играет…";
			this.needReact = true;
		}
	},
	power:function() {
		if (this.powerButton.checked) {
		} else {
			this.switchEnabled(false);
			this.disable(document.getElementById('vkcontrols-playlistbutton'));
		}
		this.page.loadURI(this.powerButton.checked?"http://vk.com/audio":"about:blank");
	},
	playPauseTrack:function() {
		if (!this.needReact) return;
		if (this.w.audioPlayer.player.paused()) this.w.audioPlayer.playTrack();
		else this.w.audioPlayer.pauseTrack();
	},
	prevTrack:function() {
		this.w.audioPlayer.prevTrack(true);
		this.popupNowPlaing();
	},
	repeatTrack:function() {
		var win = Components.classes['@mozilla.org/embedcomp/window-watcher;1'].getService(Components.interfaces.nsIWindowWatcher).openWindow(null, "chrome://vkcontrols/content/alert.xul", "_blank", "chrome,titlebar=no,popup=yes", null);  
		win.arguments = ["chrome://vkcontrols/content/play.png", "title", "msg", false, ""];
		if (!this.needReact) return;
		this.w.audioPlayer.toggleRepeat();
	},
	nextTrack:function() {
		this.w.audioPlayer.nextTrack(true);
		this.popupNowPlaing();
	},
	setVolume:function() {
		if (!this.needReact || this.volumeSlider.disabled) return;
		this.w.audioPlayer.player.setVolume(this.volumeSlider.value / 100.0);
	},
	setPosition:function() {
		if (!this.needReact || this.positionSlider.disabled) return;
		this.w.audioPlayer.player.playAudio(this.w.audioPlayer.duration * this.positionSlider.value / 100.0);
	},
	toggleSpeaker: function() {
		if (!this.needReact || this.positionSlider.disabled) return;
		this.w.audioPlayer.toggleStatus();
	},
	time:function(seconds) {
		var time = new Date(seconds * 1000);
		return ((time.getUTCHours() > 0)?this.padLeft(time.getUTCHours(), 2) + ":":"") + this.padLeft(time.getUTCMinutes(), 2) + ":" + this.padLeft(time.getUTCSeconds(), 2);
	},
	trackContextMenu: function() {
		if (this.playlist.view.selection.getRangeCount() == 0 || this.allTracksButton.checked) {
			this.disable(this.cmd_playTrack);
			this.disable(this.cmd_addTrack);
			if (this.playlist.view.selection.getRangeCount() != 0) this.enable(this.cmd_playTrack);
			else this.disable(this.cmd_playTrack);
			return;
		}
		this.enable(this.cmd_playTrack);
		if (this.recomendedTracksButton.checked || this.popularTracksButton.checked || this.searchButton.checked) this.enable(this.cmd_addTrack);
		else this.disable(this.cmd_addTrack);
		if (this.recomendedTracksButton.checked) this.enable(this.cmd_noRecommend);
		else this.disable(this.cmd_noRecommend);
	},
	playTrack: function() {
		if (this.playlist.view.selection.getRangeCount() == 0) return;
		var aid = this.rowInfo(this.playlist.currentIndex).aid;
		this.w.playAudioNew(aid);
		this.popupNowPlaing();
	},
	addTrack: function() {
		if (this.playlist.view.selection.getRangeCount() == 0) return;
		var aid = this.rowInfo(this.playlist.currentIndex).aid;
		this.d.getElementById("audio_add" + aid).click();
	},
	noRecommend: function() {
		if (this.playlist.view.selection.getRangeCount() == 0) return;
		var aid = this.rowInfo(this.playlist.currentIndex).aid;
		this.d.getElementById("remove" + aid).click();
		this.playlist.view.removeItemAt(this.playlist.currentIndex);
	},
	unesc:function(s) {
		var el = document.createRange().createContextualFragment('<div>' + s + '</div>');
		return el.textContent;
	},
	_:function(key) {
		this.strings.getString(key);
	},
	removeHTMLTags:function(text) {
		text = text.replace(/&(lt|gt);/g, function (strMatch, p1) {
			return (p1 == "lt")? "<" : ">";
		});
		var strTagStrippedText = text.replace(/<\/?[^>]+(>|$)/g, "");
		return strTagStrippedText;
	},
	makeRow:function(n, id, artist, title, duration) {
		var row = document.createElement("listitem");
		row.setAttribute("recordId", id);
		var cell = document.createElement('listcell');
		cell.setAttribute("label", n + ". " + artist + " - " + title);
		cell.setAttribute("crop", "center");
		row.appendChild(cell);
		cell = document.createElement("listcell");
		cell.setAttribute("label", duration);
		cell.setAttribute("align", "right");
		row.appendChild(cell);
		row.tooltipText = artist + " - " + title;
		return row;
	},
	get searchResults() {
		return this.w.cur.curSection == "all" && this.w.cur.searchStr;
	},
	rowInfo: function(n) {
		var id = this.searchResults?
			vkcontrols.w.cur.sContent.children[n].children[1].children[0].name:
			Object.keys(vkcontrols.treeView.data)[n];
		return this.searchResults?
			{aid: id, artist: this.removeHTMLTags(this.w.cur.sContent.children[n].children[1].children[1].children[0].children[0].children[1].children[1].children[0].innerHTML), title: this.removeHTMLTags(this.w.cur.sContent.children[n].children[1].children[1].children[0].children[0].children[1].children[1].children[1].innerHTML), duration: this.w.cur.sContent.children[n].children[1].children[1].children[0].children[0].children[1].children[0].innerHTML}:
			{aid: id, artist: this.unesc(this.treeView.data[id][5]), title: this.unesc(this.treeView.data[id][6]), duration: this.treeView.data[id][4]};
	},
	treeView: {
		data: new Object,
		get rowCount() {
			return vkcontrols.searchResults?
				vkcontrols.w.cur.sContent.children.length:
				Object.keys(vkcontrols.treeView.data).length;
		},
		getCellText: function(row, column) {
			var info = vkcontrols.rowInfo(row);
			switch (column.id) {
				case "number":
					return row + 1;
				case "artist":
					return info.artist;
				case "title":
					return info.title;
				case "duration":
					return info.duration;
			}
		},
		setTree: function(treebox) { vkcontrols.treeView.treebox = treebox; },
		isContainer: function(row) { return false; },
		isSeparator: function(row) { return false; },
		isSorted: function() { return false; },
		getLevel: function(row) { return 0; },
		getImageSrc: function(row,col) { return null; },
		getRowProperties: function(row, props) {
			var aid = vkcontrols.rowInfo(row).aid;
			if (!vkcontrols.w.audioPlayer.lastSong || vkcontrols.w.audioPlayer.lastSong[0] + "_" + vkcontrols.w.audioPlayer.lastSong[1] != aid) return;
			var aserv=Components.classes["@mozilla.org/atom-service;1"].getService(Components.interfaces.nsIAtomService);
			props.AppendElement(aserv.getAtom("currentlyPlaingTrack"));
		},
		getCellProperties: function(row, col, props) {},
		getColumnProperties: function(colid, col, props) {}
	},
	preparePlaylist:function() {
		while (this.playlist.itemCount > 0) this.playlist.removeItemAt(0);
		this.treeView.data = this.w.audioPlaylist;
		this.playlist.view = this.treeView;
		if (!this.w.audioPlayer.lastSong) return;
		var nowPlaingIndex = this.searchResults?0:Object.keys(this.w.audioPlaylist).indexOf(this.w.audioPlayer.lastSong[0] + "_" + this.w.audioPlayer.lastSong[1]);
		this.playlist.treeBoxObject.ensureRowIsVisible(nowPlaingIndex);
	},
	loadAllTracks:function() {
		this.shuffleButton.disabled = false;
		this.w.Audio.loadAlbum(0);
	},
	loadRecomendedTracks:function() {
		this.shuffleButton.disabled = false;
		this.w.Audio.loadRecommendations(true);
	},
	loadPopularTracks:function() {
		this.shuffleButton.disabled = false;
		this.w.Audio.loadPopular(true);
	},
	search:function() {
		this.shuffleButton.disabled = true;
		this.w.cur.searchStr = this.searchQuery.value;
		this.w.Audio.searchAudios(this.searchQuery.value, "all");
	},
	shuffle:function() {
		this.w.Audio.mixAudios();
	},
	rowDoubleClicked:function(event) {
		var i = this.playlist.treeBoxObject.getRowAt(event.clientX, event.clientY);
		if (i < 0) return;
		this.w.playAudioNew(this.rowInfo(i).aid);
		this.popupNowPlaing();
	},
	rowClicked:function(event) {
		var i = this.playlist.treeBoxObject.getRowAt(event.clientX, event.clientY);
		if (i < 0) this.playlist.view.selection.clearSelection();
		else this.playlist.view.selection.select(i);
	},
}

window.addEventListener("load", function() {
	vkcontrols.cmd_addTrack = document.getElementById("cmd_addTrack");
	vkcontrols.cmd_playTrack = document.getElementById("cmd_playTrack");
	vkcontrols.cmd_noRecommend = document.getElementById("cmd_noRecommend");
	vkcontrols.speaker = document.getElementById("vkcontrols-speakerbutton");
	vkcontrols.powerButton = document.getElementById("vkcontrols-powerbutton");
	vkcontrols.playPauseButton = document.getElementById("vkcontrols-playpausebutton");
	vkcontrols.repeatButton = document.getElementById("vkcontrols-repeatbutton");
	vkcontrols.volumeSlider = document.getElementById("vkcontrols-volume");
	vkcontrols.positionSlider = document.getElementById("vkcontrols-position");
	vkcontrols.positionProgress = document.getElementById("vkcontrols-position-progress");
	vkcontrols.positionLabel = document.getElementById("vkcontrols-position-label");
	vkcontrols.trackName = document.getElementById("vkcontrols-track-name");
	vkcontrols.volumeLabel = document.getElementById("vkcontrols-volume-label");
	vkcontrols.strings = document.getElementById("vkcontrols-string-bundle");
	vkcontrols.page = document.getElementById("page");
	vkcontrols.searchQuery = document.getElementById("vkcontrols-search-query");
	vkcontrols.playlistPanel = document.getElementById("vkcontrols-playlist-panel");
	vkcontrols.playlist = document.getElementById("vkcontrols-playlist");
	vkcontrols.allTracksButton = document.getElementById("vkcontrols-all-tracks-button");
	vkcontrols.recomendedTracksButton = document.getElementById("vkcontrols-recommended-tracks-button");
	vkcontrols.popularTracksButton = document.getElementById("vkcontrols-popular-tracks-button");
	vkcontrols.searchButton = document.getElementById("vkcontrols-find-tracks-button");
	vkcontrols.shuffleButton = document.getElementById("vkcontrols-shuffle-button");
	vkcontrols.addTrackButton = document.getElementById("vkcontrols-playlist-popup-addTrack");
	vkcontrols.noRecommendButton = document.getElementById("vkcontrols-playlist-popup-noRecommend");
	vkcontrols.playlist.addEventListener("dblclick", function(event) {
		var target = event.target;
		while (target && target.localName != "listitem") target = target.parentNode;
		if (!target) return;
		vkcontrols.w.playAudioNew(target.getAttribute("recordId"));
		vkcontrols.preparePlaylist();
	}, false);
	vkcontrols.page.addEventListener("load", function(e) {
		if (e.target == vkcontrols.page.contentDocument) {
			if (vkcontrols.page.currentURI.scheme == "http") {
				vkcontrols.d = vkcontrols.page.contentDocument;
				if (vkcontrols.page.currentURI.path.substr(0, 6) == "/audio") {
					vkcontrols.enable(document.getElementById('vkcontrols-playlistbutton'));
					vkcontrols.w = vkcontrols.page.contentWindow.wrappedJSObject;
					vkcontrols.w.Notifier.init = function(options) {}
					vkcontrols.w.audioPlayer.onLoadProgressOld = vkcontrols.w.audioPlayer.onLoadProgress;
					vkcontrols.w.audioPlayer.onLoadProgress = function(bLoaded, bTotal) {
						vkcontrols.w.audioPlayer.onLoadProgressOld(bLoaded, bTotal);
						vkcontrols.positionProgress.style.marginLeft = (bTotal == 0)?"10px":(10 + 230.0 * bLoaded / bTotal) + "px";
					}
					vkcontrols.w.audioPlayer.onPlayProgressOld = vkcontrols.w.audioPlayer.onPlayProgress;
					vkcontrols.w.audioPlayer.onPlayProgress = function(pos, len) {
						vkcontrols.w.audioPlayer.onPlayProgressOld(pos, len);
						vkcontrols.needReact = false;
						vkcontrols.positionSlider.value = (len == 0)?0:100.0 * pos / vkcontrols.w.audioPlayer.duration;
						vkcontrols.positionLabel.value = (len == 0 || vkcontrols.w.audioPlayer.duration < pos)?"--:--":vkcontrols.time(vkcontrols.w.audioPlayer.duration - pos);
						vkcontrols.trackName.value = vkcontrols.trackName.tooltipText = (vkcontrols.w.audioPlayer.lastSong)?vkcontrols.unesc(vkcontrols.w.audioPlayer.lastSong[5]) + " - " + vkcontrols.unesc(vkcontrols.w.audioPlayer.lastSong[6]):"Ничего не играет…";
						vkcontrols.needReact = true;
					}
					vkcontrols.w.audioPlayer.onPlayFinishOld = vkcontrols.w.audioPlayer.onPlayFinish;
					vkcontrols.w.audioPlayer.onPlayFinish = function() {
						vkcontrols.w.audioPlayer.onPlayFinishOld();
						vkcontrols.preparePlaylist();
						vkcontrols.popupNowPlaing();
					}
					vkcontrols.w.Audio.genPlaylistOld = vkcontrols.w.Audio.genPlaylist;
					vkcontrols.w.Audio.genPlaylist = function(res, copyToMain) {
						vkcontrols.w.Audio.genPlaylistOld(res, true);
						vkcontrols.preparePlaylist();
					}
					vkcontrols.w.Audio.setQLocOld = vkcontrols.w.Audio.setQLoc;
					vkcontrols.w.Audio.setQLoc = function(query) {
						vkcontrols.w.Audio.setQLocOld(query);
						if (query) vkcontrols.preparePlaylist();
					}
					vkcontrols.w.Audio.generateAlbumsOld = vkcontrols.w.Audio.generateAlbums;
					vkcontrols.w.Audio.generateAlbums = function() {
						vkcontrols.w.Audio.generateAlbumsOld();
						if (vkcontrols.w.cur.audiosList.all.length == 0) return;
						var firstId = vkcontrols.w.cur.audiosList.all[0][0] + "_" + vkcontrols.w.cur.audiosList.all[0][1];
						vkcontrols.w.playAudioNew(firstId);
						vkcontrols.w.playAudioNew(firstId);
					}
					if (vkcontrols.timer) clearInterval(vkcontrols.timer);
					vkcontrols.timer = setInterval(
						function() {
							if (vkcontrols.w.audioPlayer && vkcontrols.w.audioPlayer.player) {
								vkcontrols.switchEnabled(true);
								vkcontrols.needReact = false;
								vkcontrols.playPauseButton.checked = !vkcontrols.w.audioPlayer.player.paused();
								vkcontrols.repeatButton.checked = vkcontrols.w.audioPlayer.repeat;
								vkcontrols.volumeSlider.value = vkcontrols.w.audioPlayer.player.getVolume() * 100.0;
								vkcontrols.positionSlider.value = vkcontrols.w.audioPlayer.position / vkcontrols.w.audioPlayer.duration * 100.0;
								vkcontrols.volumeLabel.value = Math.round(vkcontrols.w.audioPlayer.player.getVolume() * 100);
								vkcontrols.speaker.checked = vkcontrols.w.audioPlayer.statusExport;
								vkcontrols.needReact = true;
							} else {
								vkcontrols.switchEnabled(false);
							}
						}, 100);
				} else {
					var params = {login:false};
					var b = window.openDialog("chrome://vkcontrols/content/login.xul", "login", "chrome, dialog, modal, centerscreen", params).focus();
					if (params.out) {
						var doc = vkcontrols.page.contentDocument;
						var quick = doc.getElementById("quick_login_form");
						var form = quick?quick:doc.getElementById("login");
						var email = doc.getElementById(quick?"quick_email":"email");
						var pass =  doc.getElementById(quick?"quick_pass":"pass");
						var expire =  doc.getElementById(quick?"quick_expire_input":"expire");
						email.value = params.out.email;
						pass.value = params.out.pass;
						expire.value = params.out.expire?"1":"";
						form.submit();
					} else vkcontrols.powerButton.checked = false;
				}
			} else {
				vkcontrols.w = null;
				if (vkcontrols.timer) clearInterval(vkcontrols.timer);
				vkcontrols.switchEnabled(false);
			}
		}
	}, true);
}, false);